package com.heima.behavior.filter;

import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.thread.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
@Order(0)
@Component
public class AppTokenFilter extends GenericFilterBean {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String id = request.getHeader("userId");
        if (id != null && Integer.parseInt(id) != 0 ){
            ApUser apUser = new ApUser();
            apUser.setId(Integer.parseInt(id));
            AppThreadLocalUtils.setUser(apUser);
        }
        filterChain.doFilter(servletRequest,servletResponse);
        AppThreadLocalUtils.clean();
    }
}
